package com.czie.myapplication;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import java.io.IOException;
import java.util.List;

public class GatherService extends IntentService {
    private int temp;
    private String gateWayId = MainActivity.GATEWAYID;
//    private String gateWayId ="00000008";

    public GatherService() {
        super("gather");
    }


    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Bundle bundle = intent.getExtras();

        Log.i("Server:", "================启动");
        gateWayId = bundle.getString("code");
        SensorManager manager = SensorManager.getManager();

        while (true) {
//            //扫描串口服务器地址
//            if (manager.scanSerialServer() == null) {
//                continue;
//            }

            Log.i("SCAN", "Serial server IP:" + manager.getSerialServerIp());
            //连接串口服务器，连接失败等3秒重连
            if (!manager.connectSerialServer()) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                continue;
            }
            //循环的接收串口服务器的数据，接收失败的时候结束循环，重新连接
            while (true) {
                try {
                    // 将接收到的传感器信息存放在packets中
                    List<DataPacket> packets = manager.receiveData();
                    if (packets == null) {
                        continue;
                    }
                    for (DataPacket packet : packets) {
//                    	Log.d("GGGGG", "TYPE:"+packet.getSensorType()+",VALUE="+packet.getSensorData());
                        // 广播发送传感器的信息
                        this.sendBroadcast(packet);
                    }
                } catch (IOException e) {
                    Log.e("EEEEEEE", "Lost connection from serial server");
                    break;
                }
            }
        }
    }

    // 发送广播
    private void sendBroadcast(DataPacket packet) {
        final Intent intent1 = new Intent("ReceiveData");
        // 创建文件对象
        Bundle bundle1 = new Bundle();
        // 获取传感器对应的数据，存在Bundle文件中
        bundle1.putString("sensorId", packet.getSensorId());
        bundle1.putInt("sensorType", packet.getSensorType());
        bundle1.putString("data", packet.getSensorData());
        intent1.putExtras(bundle1);
        //调用系统广播将消息发送出去
        sendBroadcast(intent1);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("BBBBB", "bind service");
        return super.onBind(intent);
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        Log.i("CCCCC", "Start command");
        return super.onStartCommand(intent, flags, startId);
    }

}
